package com.foreveross.fetl.queue;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;

import com.foreveross.fetl.util.DataBaseFetlUtils;
import com.foreveross.fetl.util.DateUtils;
import com.foreveross.fetl.util.StringUtils;

public class DeleteTableRow {
	private static Logger log = Logger.getLogger("deleteTableRow");
	
	public void execute() {
	//	deleteTableRow();
		trunCatePlanInfo();
		deleteData();
	}
/*	private void deleteTableRow() {
			ResultScanner rs = null;
			try {
				HBaseHelper.delAllRecord("LP_FLIGHT_DOUBLE");
			} catch (Exception e1) {
				log.error(StringUtils.getStackTrace(e1));
			}finally {
				if (rs != null)
					rs.close();
				rs = null;
			}
	}*/
	
	/**
	 * 清空 mysql表
	 */
	private void trunCatePlanInfo(){
		
		List<String> tables=new ArrayList<String>();
		tables.add("planeinfo");
		tables.add("planeinfo_json");
		tables.add("planeinfo_double");
		tables.add("planeinfo_json_double");
		tables.add("line_day");
		tables.add("csair_report");
		
		String day=DateUtils.format(new Date(), "dd");
		if(day.equals("01") || day.equals("15")){
			tables.add("air_spread");
			tables.add("airchina_domestic");
			tables.add("airchina_international");
			tables.add("airchina_taobao");
			tables.add("csair_taobao");
		}
		
		final String sql=" TRUNCATE TABLE ";
		
		Connection conn =null;
		PreparedStatement stmt = null;  
		
		try {
			for(String tableName:tables){
				conn = DataBaseFetlUtils.getConnection();
				stmt =conn.prepareStatement(sql+tableName);
				stmt.execute();
			}
		} catch (SQLException e) {
			log.error(StringUtils.getStackTrace(e));
		}finally {
			if(null!=stmt){
				try {
					stmt.close();
				} catch (SQLException e) {
					log.error(StringUtils.getStackTrace(e));
				}
			}
			if(null!=conn){
				try {
					conn.close();
				} catch (SQLException e) {
					log.error(StringUtils.getStackTrace(e));
				}
			}
		}
		
	}
	
	private void deleteData(){
		Calendar cday =Calendar.getInstance();
		cday.add(Calendar.DAY_OF_MONTH, -10);
		String oldDateStr=DateUtils.format(cday.getTime(), "yyyy-MM-dd");
		Connection conn =null;
		PreparedStatement stmt = null;  
		try {
			conn = DataBaseFetlUtils.getConnection();
			stmt =conn.prepareStatement("DELETE FROM offic_channel_spread WHERE GRAB_TIME< '"+oldDateStr+"'");
			stmt.execute();
			stmt =conn.prepareStatement("DELETE FROM official_plus_day WHERE CREATE_TIME< '"+oldDateStr+"'");
			stmt.execute();
		} catch (SQLException e) {
			log.error(StringUtils.getStackTrace(e));
		}finally {
			if(null!=stmt){
				try {
					stmt.close();
				} catch (SQLException e) {
					log.error(StringUtils.getStackTrace(e));
				}
			}
			if(null!=conn){
				try {
					conn.close();
				} catch (SQLException e) {
					log.error(StringUtils.getStackTrace(e));
				}
			}
		}
	}
	
}
